<template>
<div></div>
</template>

<script>
import {useStore} from "vuex";
import {ElButton, ElMessage, ElNotification} from "element-plus";
import {h, watch} from "vue";
import router from "@/router";

export default {

  setup(){
    const store = useStore();
    const connectMessage = () =>{
      if(store.state.websocket.socket) {
        console.log("进来了");
        store.state.websocket.socket.onmessage = (msg) => {
          console.log("收到一条信息");
          const data = JSON.parse(msg.data);
          console.log(data);
          //////////////////////FRIEND_REQUEST_EVENT////////////////好友请求
          if (data.event === "FRIEND_REQUEST_EVENT") {
            store.dispatch("getFriendRequest", {
              success() {
                console.log("请求好友成功");
              },
              error(resp) {
                // ElMessage.error(resp);
                console.log("有好友信息来了，但是获取失败", resp);
              }
            })

            const notificationInstance = ElNotification({
              title: '好友邀请',
              duration: 2000, // 设置为0表示不自动消失
              showClose: true,
              type: 'info',
              customClass: 'my-notification',//复杂的设计，弹窗中的按钮跳转详情页面，并关闭弹窗
              message: () => {
                return h('div', [
                  h('span',{ style: { marginRight: '20px' } }, '你有一个好友邀请信息'),
                  h(ElButton, {
                    type: 'primary',
                    size: 'small',

                    onClick: () => {
                      // 点击按钮后关闭通知
                      notificationInstance.close(); // 关闭当前通知
                      router.push({ path: "/receive_friend/" }); // 跳转到好友请求页面
                    },
                  }, () =>'查看')
                ]);
              },
            });
          }
          /////////////////////////////////////
          else if(data.event ===  "USER_LOGIN_EVENT" || data.event === "USER_LOGOUT_EVENT" || data.event === "USER_QUIT_ROOM_EVENT" || data.event === "USER_CREATE_ROOM_EVENT" || data.event === "USER_STATUS_UPDATE_EVENT"){////用户状态更改事件
            console.log("进来了2")
            store.dispatch("getFriends", {
              success() {
                //这里会自动更新好友状态
                // ElMessage.success(resp);
              },
              error(resp) {
                ElMessage.error(resp);
              }
            });
            if(data.event === "USER_QUIT_ROOM_EVENT"){
              if(data.senderId === store.state.user.userId){
                console.log("离开了房间");
                store.commit("clearAllPkInfo");
              }
              else if(data.senderId === store.state.pk.opponentId){
                console.log("离开了房间");
                store.commit("clearOpponentPkInfo");
              }

            }
          }
          else if(data.event === "ROOM_CLOSED_BY_OWNER_EVENT"){
            store.commit("updateStatus","loading");
            store.commit("updateLoser","none");
            store.commit("updateRoomId",{
              roomId:"-1",
              isRoomUser:false
            })
            ElMessage.warning("房主已关闭房间");
          }
          else if(data.event === "INVITE_EVENT"){
            const notificationInstance = ElNotification({
              title: '好友邀请',
              duration: 5000, // 设置为0表示不自动消失
              showClose: true,
              type: 'warning',
              customClass: 'my-notification',
              message: () => {
                return h('div', [
                  h('span',{ style: { marginRight: '20px' } }, '你有一个对战邀请信息'),
                  h(ElButton, {
                    type: 'primary',
                    size: 'small',

                    onClick: () => {
                      store.dispatch("acceptInvite", {
                        inviteKey:data.data,
                        senderId:data.senderId,
                        token:store.state.user.token,
                        success(resp) {
                          ElMessage.success(resp);
                          // console.log("请求好友成功");
                        },
                        error(resp) {
                          ElMessage.error(resp);
                          // console.log("有好友信息来了，但是获取失败", resp);
                        }
                      })

                      notificationInstance.close(); // 关闭当前通知
                    },
                  }, () =>'同意'),
                  h(ElButton, {
                    type: 'primary',
                    size: 'small',

                    onClick: () => {
                      notificationInstance.close(); // 关闭当前通知
                    },
                  }, () => '拒绝')
                ]);
              },
            });
          }
          else if(data.event === "INVITE_ACCEPT_EVENT") {
            store.dispatch("getFriends", {
              success() {
                //这里会自动更新好友状态
                // ElMessage.success(resp);
              },
              error(resp) {
                ElMessage.error(resp);
              }
            });

            if (store.state.pk.roomId === data.data.roomId) {
              store.commit("updateOpponent", {
                username: data.data.playerInfoList[1].username,
                photo: data.data.playerInfoList[1].avatarUrl,
                id: data.data.playerInfoList[1].userId,
              })
            } else if (store.state.user.userId === data.data.playerInfoList[1].userId) {
              store.commit("updateOpponent", {
                username: data.data.playerInfoList[0].username,
                photo: data.data.playerInfoList[0].avatarUrl,
                id: data.data.playerInfoList[0].userId,
              })
              store.commit("updateRoomId", {roomId: data.data.roomId});
              store.commit("updateStatus", "matching");
              router.push({name: "map_index"});
            }
          }
          else if(data.event === "PLAYER_READY_EVENT"){
            if(store.state.pk.isRoomUser){
              store.commit("updateIsReady",true);
            }
          }
          else if(data.event === "PLAYER_CANCEL_READY_EVENT"){

            if(store.state.pk.isRoomUser){

              store.commit("updateIsReady",false);
              console.log(store.state.pk.isReady);
            }
          }
          else if(data.event === "GAME_STARTED_EVENT"){


            if(store.state.pk.isRoomUser){
              store.commit("updateIsMe",true);
              store.commit("updateIAmBlack",true);
            }
            else{
              store.commit("updateIsMe",false);
              store.commit("updateIAmBlack",false);
            }
            store.commit("updateStatus","playing");
          }
          else if(data.event === "NEXT_PLAYER_MOVE_EVENT"){
            store.state.pk.gameObject.add_a_point(data.data.row,data.data.col,!store.state.pk.iAmBlack);
            setTimeout(() => {
              store.commit("updateIsMe",true);
              // console.log("延迟一秒后执行:", this.timestampInMilliseconds);
            }, 500); // 延迟500毫秒（0.5秒）
          }
          else if(data.event === "GAME_LOSE_EVENT" || data.event === "GAME_WIN_EVENT"){//游戏结束的5子渲染
            let k = 0;
            if(store.state.pk.gameObject.resultArr[data.data[0][0]][data.data[0][1]] === -1)
              k = 3;
            else if(store.state.pk.gameObject.resultArr[data.data[0][0]][data.data[0][1]] === 1)
              k = 5;
            store.state.pk.gameObject.timestamp = Date.now();
            for(let i = 0 ; i < 5;i++){
              store.state.pk.gameObject.resultArr[data.data[i][0]][data.data[i][1]] = k;
            }
            if(data.event === "GAME_LOSE_EVENT"){//失败
                setTimeout(() => {
                  store.commit("updateLoser","you")
                }, 2000); // 延迟
            }
            else if(data.event === "GAME_WIN_EVENT"){//胜利
                setTimeout(() => {
                  store.commit("updateLoser","he")
                }, 2000); // 延迟
            }
          }
          else if(data.event === "GAME_DRAW_EVENT"){//平局
            store.commit("updateLoser","all");
          }
          else if(data.event === "OPPONENT_DISCONNECTED_EVENT"){//用户退出房间事件
            if(store.state.pk.isRoomUser){
              // store.commit("clearOpponentPkInfo");//清空对手数据
              store.commit("clearAllPkInfo");
              store.commit("updateStatus","loading");
              ElMessage.warning("对手已离开房间，你已自动胜利");

              // store.commit("updateLoser","he");//我胜利
            }
            else{
              store.commit("clearAllPkInfo");
              ElMessage.warning("房主已关闭房间，你已自动胜利");
              store.commit("updateStatus","loading");
            }
          }
          else if(data.event === "GAME_MATCH_SUCCESS"){//用户匹配成功事件
            if(data.data.currentPlayerId === store.state.user.userId){
              store.commit("updateRoomId",{
                roomId:data.data.roomId,
                isRoomUser:true,
              })
              store.commit("updateIsMe",true);
              store.commit("updateIAmBlack",true);
              store.commit("updateOpponent", {
                username: data.data.playerInfoList[1].username,
                photo: data.data.playerInfoList[1].avatarUrl,
                id: data.data.playerInfoList[1].userId,
              })
            }
            else{
              store.commit("updateRoomId",{
                roomId:data.data.roomId,
                isRoomUser:false,
              })
              store.commit("updateIsMe",false);
              store.commit("updateIAmBlack",false);
              store.commit("updateOpponent", {
                username: data.data.playerInfoList[0].username,
                photo: data.data.playerInfoList[0].avatarUrl,
                id: data.data.playerInfoList[0].userId,
              })
            }

            setTimeout(() => {
              store.commit("updateStatus","playing");
            }, 2000); // 延迟


          }

        }

        // commit('ADD_MESSAGE', data); // 将消息存储到 state,不过不是什么都要加入message
      }

    }
    // 监视 socket 状态
    watch(
        () => store.state.websocket.socket,
        (newSocket) => {
          if (newSocket) {
            connectMessage(); // 当 socket 更新后，调用 connectMessage
          }
        }
    );
    connectMessage();
    return {
      connectMessage,
    }
  }
}
</script>

<style scoped>
.my-notification {
  min-width: 40px;

}
</style>